import path from 'path'
import fs from 'fs'
import mdContainer from 'markdown-it-container'
// import { docsRoot } from '@yf-lib/build-utils'
import MarkdownIt from 'markdown-it'

const projRoot = path.resolve(__dirname, '..', '..')
const docsRoot = path.resolve(projRoot, 'docs')

interface ContainerOpts {
  marker?: string | undefined
  validate?(params: string): boolean
  render?(
    tokens: MarkdownIt.Token[],
    index: number,
    options: any,
    env: any,
    self: MarkdownIt.Renderer
  ): string
}

export const mdPlugin = (md: MarkdownIt, exPath: string = 'test') => {
  md.use(mdContainer as unknown as MarkdownIt.PluginWithParams, 'demo', {
    validate(params) {
      return !!params.trim().match(/^demo\s*(.*)$/)
    },

    render(tokens, idx, options) {
      const m = tokens[idx].info.trim().match(/^demo\s*(.*)$/)
      if (tokens[idx].nesting === 1 /* means the tag is opening */) {
        const description = m && m.length > 1 ? m[1] : ''
        const sourceFileToken = tokens[idx + 2]
        let source = ''
        const sourceFile = sourceFileToken.children?.[0].content ?? ''
        if (sourceFileToken.type === 'inline') {
          source = fs.readFileSync(
            path.resolve(exPath, 'examples', `${sourceFile}.vue`),
            'utf-8'
          )
        }
        if (!source) throw new Error(`Incorrect source file: ${sourceFile}`)

        return `<Demo :demos="demos" source="${encodeURIComponent(
          md.render(`\`\`\` vue\n${source}\`\`\``)
        )}" path="${sourceFile}" raw-source="${encodeURIComponent(
          source
        )}" description="${encodeURIComponent(md.render(description))}">`
      } else {
        return '</Demo>'
      }
    },
  } as ContainerOpts)

}

const htmlPlugin = () => {
  return {
    name: 'html-transform',
    transformIndexHtml(html: string) {
      return {
        html,
        tags: [{
          tag: 'script',
          attrs: {
            type: 'module',
            src: 'test.ts'
          },
          injectTo: 'body'
        }]
      } as any
    },
  }
}
